package com.jandar.service;

import com.cl.mvc.service.BaseService;
import com.jandar.entity.ExcelSourceTypeMapping;
import com.jandar.repository.ExcelSourceTypeMappingRepository;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExcelSourceTypeMappingService extends BaseService<ExcelSourceTypeMapping> {
    protected ExcelSourceTypeMappingService(ExcelSourceTypeMappingRepository ExcelSourceTypeMappingRepository) {
        super(ExcelSourceTypeMappingRepository);
    }

    public void generateExcel(Integer typeId, HttpServletResponse response) throws IOException {
        List<ExcelSourceTypeMapping> typeMappings = findByField("typeId", String.valueOf(typeId));
        List<String> headers = typeMappings.stream().map(ExcelSourceTypeMapping::getFromKey).collect(Collectors.toList());;
        generateExcelWithHeaders(headers,response);
    }

    public static void generateExcelWithHeaders(List<String> headers, HttpServletResponse response) throws IOException {
        Workbook workbook = new XSSFWorkbook(); // 创建新的Workbook
        Sheet sheet = workbook.createSheet("Sheet1"); // 创建一个Sheet

        // 创建表头
        Row headerRow = sheet.createRow(0); // 第一行作为表头
        for (int i = 0; i < headers.size(); i++) {
            Cell cell = headerRow.createCell(i); // 创建单元格
            cell.setCellValue(headers.get(i)); // 设置单元格值
        }

        // 这里你可以继续添加数据行...

        // 将Workbook写入文件
        workbook.write(response.getOutputStream());

        // 关闭Workbook
        workbook.close();
    }
}
